package com.moli.iov.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.sys.mapper.UserRoleMapper;
import com.moli.iov.sys.model.po.UserRole;
import com.moli.iov.sys.service.IUserRoleService;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户角色业务
 * </p>
 *
 * @author zql
 * @since 2019/9/9 13:06
 */
@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements
    IUserRoleService {

  /**
   * 设置用户角色
   * @param userRole
   * @return
   */
  @Override
  public boolean setUserRole(UserRole userRole) {
    deleteUserRole(userRole);
    return saveUserRole(userRole);
  }

  /**
   * 添加用户角色
   * @param userRole
   * @return
   */
  @Override
  public boolean saveUserRole(UserRole userRole) {
    return super.save(userRole);
  }

  /**
   * 删除用户角色
   * @param userRole
   * @return
   */
  @Override
  public boolean deleteUserRole(UserRole userRole) {
    QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("user_id", userRole.getUserId());
    return super.remove(queryWrapper);
  }

  /**
   * 根据用户id，获取用户角色列表
   * @param userRole
   * @return
   */
  @Override
  public List<UserRole> listUserRoleByUserId(UserRole userRole) {
    QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("user_id", userRole.getUserId());
    return super.list(queryWrapper);
  }

  /**
   * 查询角色 ids, by用户id
   * @param userId
   * @return
   */
  @Override
  public List<Long> listRoleIdsByUserId(Long userId) {

    UserRole userRole = new UserRole();
    userRole.setUserId(userId);
    List<UserRole> userRoles = listUserRoleByUserId(userRole);

    List<Long> roleIds = new ArrayList<>();
    userRoles.forEach(ur -> roleIds.add(ur.getRoleId()));
    return roleIds;
  }

  /**
   * 查询用户ids
   * @param roleId
   * @return
   */
  @Override
  public List<Long> listUserIdByRoleId(Long roleId) {
    QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("role_id", roleId);
    List<UserRole> userRoles = super.list(queryWrapper);

    List<Long> userIds = new ArrayList<>();
    userRoles.forEach(ur -> userIds.add(ur.getUserId()));
    return userIds;
  }
}
